/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package storymotion.storytelling;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import storymotion.config.Configuration;
import storymotion.gifmaker.GifSequenceWriter;
import storymotion.photo.Photo;
import storymotion.photo.PhotoDAO;
import storymotion.user.User;

/**
 *
 * @author Leonardo Oliveira Moreira
 */
public class StorytellingInsert extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();

        User user = (User) session.getAttribute("user");
        String[] photoIds = request.getParameter("photoIds").split(";");
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        boolean loopContinuously = (request.getParameter("loopContinuously") != null && request.getParameter("loopContinuously").equals("1")) ? true : false;
        int delay = Integer.parseInt(request.getParameter("delay"));

        PhotoDAO photoDAO = null;
        StorytellingDAO storytellingDAO = null;
        List<Photo> photoList = new ArrayList<Photo>();
        try {
            photoDAO = new PhotoDAO();
            storytellingDAO = new StorytellingDAO();
            for (String photoIdStr : photoIds) {
                long photoId = Long.parseLong(photoIdStr);
                Photo photo = photoDAO.getById(photoId);
                photoList.add(photo);
            }
            photoDAO.commit();
            if (photoList.size() > 0) {
                String fileName = Configuration.STORYTELLINGPATH + user.getLogin() + "_" + System.nanoTime() + ".gif";

                Storytelling storytelling = new Storytelling();
                storytelling.setFileName(fileName);
                storytelling.setDate(new Date());
                storytelling.setDescription(description);
                storytelling.setName(name);
                storytelling.setUserId(user.getId());

                BufferedImage firstImage = ImageIO.read(new File(Configuration.PHOTOPATH + photoList.get(0).getId() + "_" + photoList.get(0).getName()));
                ImageOutputStream output = new FileImageOutputStream(new File(fileName));
                GifSequenceWriter writer = new GifSequenceWriter(output, firstImage.getType(), delay, loopContinuously);
                writer.writeToSequence(firstImage);
                for (int i = 1; i < photoList.size() - 1; i++) {
                    BufferedImage nextImage = ImageIO.read(new File(Configuration.PHOTOPATH + photoList.get(i).getId() + "_" + photoList.get(i).getName()));
                    writer.writeToSequence(nextImage);
                }
                writer.close();
                output.close();
                
                storytellingDAO.insert(storytelling);
                storytellingDAO.commit();
                
                request.setAttribute("message", "Photo successfully registered");
                request.getRequestDispatcher("MainServlet").forward(request, response);
            } else {
                throw new SQLException("Failed to create storytelling");
            }
        } catch (SQLException ex) {
            if (photoDAO != null) {
                try {
                    photoDAO.rollback();
                } catch (SQLException ex1) {
                }
            }
            if (storytellingDAO != null) {
                try {
                    storytellingDAO.rollback();
                } catch (SQLException ex1) {
                }
            }
            request.setAttribute("message", ex.getMessage());
            request.getRequestDispatcher("MainServlet").forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
